package com.emm.yixun.customer.service.impl.app.manage;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.basic.service.AppPushService;
import com.emm.yixun.basic.service.BusinessAbnormaService;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DictionaryService;
import com.emm.yixun.basic.service.FamilyMemberService;
import com.emm.yixun.basic.service.ImageService;
import com.emm.yixun.basic.service.MessageReceiverService;
import com.emm.yixun.basic.service.NoticeService;
import com.emm.yixun.basic.service.PriceSchemeDetailService;
import com.emm.yixun.basic.service.ProjectRoomService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.basic.service.ProjectSettingService;
import com.emm.yixun.basic.service.SubscribeService;
import com.emm.yixun.basic.service.TransactionRelationService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.app.EditSubscribeReqDto;
import com.emm.yixun.common.app.EditSubscribeResDto;
import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.app.servletentity.CustomerFamilyListReq;
import com.emm.yixun.common.app.servletentity.ImageListReq;
import com.emm.yixun.common.enums.ProcessTypeEnums;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.model.BusinessAbnorma;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.Dictionary;
import com.emm.yixun.common.model.FamilyMember;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.ProjectSetting;
import com.emm.yixun.common.model.Subscribe;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.BusinessAbnormaDto;
import com.emm.yixun.common.model.dto.CustomerDto;
import com.emm.yixun.common.model.dto.DictionaryDto;
import com.emm.yixun.common.model.dto.FamilyMemberDto;
import com.emm.yixun.common.model.dto.ImageDto;
import com.emm.yixun.common.model.dto.MessageReceiverDto;
import com.emm.yixun.common.model.dto.NoticeDto;
import com.emm.yixun.common.model.dto.ProjectRoomDto;
import com.emm.yixun.common.model.dto.ProjectSettingDto;
import com.emm.yixun.common.model.dto.SubscribeDto;
import com.emm.yixun.common.model.dto.TransactionRelationDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.enums.AuditStatusEnum;
import com.emm.yixun.common.model.enums.BusinessAbnormaEnum;
import com.emm.yixun.common.model.enums.BusinessTypeEnum;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.ImgTypeEnum;
import com.emm.yixun.common.model.enums.IsSendEnum;
import com.emm.yixun.common.model.enums.MemberTypeEnum;
import com.emm.yixun.common.model.enums.RelationTypeEnum;
import com.emm.yixun.common.model.enums.RoomStatusEnum;
import com.emm.yixun.common.model.enums.SexEnum;
import com.emm.yixun.common.utils.FileUploadPorxyUtil;
import com.emm.yixun.common.utils.MsgUtil;
import com.emm.yixun.common.utils.SequencesGenerator;
import com.emm.yixun.customer.service.impl.app.ActivitiProcessServiceImpl;

@Service("editSubscribeManage")
public class EditSubscribeManage {

	@Autowired
	private CustomerService customerService;
	@Autowired
	private SubscribeService subscribeService;
	@Autowired
	private FamilyMemberService familyMemberService;
	@Autowired
	private ProjectRoomService projectRoomService;
	@Autowired
	private ProjectSettingService projectSettingService;
	@Autowired
	private UserService userService;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private BusinessAbnormaService businessAbnormaService;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private CusAppNoticeManage cusAppNoticeManage;
	@Autowired
	private MessageReceiverService messageReceiverService;
	@Autowired
	private NoticeService noticeService;
	@Autowired
	private AppPushService appPushService;
	@Autowired
	private PriceSchemeDetailService priceSchemeDetailService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private RepositoryService repositoryService;
	@Autowired
	private TransactionRelationService transactionRelationService;
	@Autowired
	private ActivitiProcessServiceImpl activitiProcessService;
	@Autowired
	private ImageService imageService;
	@Value("${file.serviceUrl}")
	private String fileUploadUrl;
	
	/**
	 * 修改认购
	 * @param reqDto
	 * @return
	 */
	@Transactional(propagation=Propagation.REQUIRED)
	public EditSubscribeResDto editSubscribe(EditSubscribeReqDto reqDto) {
		EditSubscribeResDto resDto = new EditSubscribeResDto();
		try{
			Subscribe subscribe = subscribeService.selectById(Long.parseLong(reqDto.getSubscribeId()));
			if(subscribe == null){
				resDto.setErrorCode("00001");
				resDto.setErrorMsg("认购记录不存在!");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			String roomId = reqDto.getRoomId();
			if(StringUtils.isNotEmpty(roomId)){
				ProjectRoom room = projectRoomService.selectById(Long.parseLong(roomId));
				if(room != null){
					String roomStatus = room.getRoomStatus();
					//可售或认筹状态可认购
					if(!RoomStatusEnum.VENDIBILITY.getNo().equals(roomStatus) && !RoomStatusEnum.RESERVE.getNo().equals(roomStatus)){
						resDto.setErrorCode("00000");
						resDto.setErrorMsg("此房源状态为:"+RoomStatusEnum.getByNo(roomStatus).getDes()+",房源不可认购!");
						resDto.setResult(ResultEnum.FAILURE.getNo());
						return resDto;
					}
				} else {
					resDto.setErrorCode("00000");
					resDto.setErrorMsg("房源不存在");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}
			}
			
			//校验认购号是否重复
			if(reqDto.getSubscribeCode() != null && !"".equals(reqDto.getSubscribeCode())){
				if(!reqDto.getSubscribeCode().equals(subscribe.getSubscribeCode())){
					SubscribeDto sb_dto = new SubscribeDto();
					sb_dto.setMerchantId(reqDto.getMerchantId());
					sb_dto.setProjectCode(reqDto.getProjectCode());
					sb_dto.setSubscribeCode(reqDto.getSubscribeCode());
					List<Subscribe> subscribeList =  subscribeService.selectListByDto(sb_dto);
					if(subscribeList.size() > 0){
						resDto.setErrorCode("00000");
						resDto.setErrorMsg("已经存在该认购号!");
						resDto.setResult(ResultEnum.FAILURE.getNo());
						return resDto;
					}
				}
			}
			
			String startProcessKey_rgzk = null;
			String startProcessKey_rg = null;
			if (reqDto.getDiscountApproval().equals("1") && reqDto.getDiscountApproval() != null){
				//动态获取认购折扣流程KEY
				startProcessKey_rgzk = activitiProcessService.getProcessKey(reqDto.getMerchantId(), subscribe.getProjectId(), ProcessTypeEnums.PROCESS_KEY_17);
				if(StringUtils.isEmpty(startProcessKey_rgzk)){
					resDto.setErrorCode("0000");
					resDto.setErrorMsg("项目未设置认购折扣流程，请去项目流程菜单配置!");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}
				// 检查流程节点是否已设置人员（认购折扣审批）
				String processKey_diszk = startProcessKey_rgzk;
				boolean isSeting_diszk = activitiProcessService.checkNodeUser(reqDto.getMerchantId(), subscribe.getProjectId(), processKey_diszk);
				if (!isSeting_diszk) {
					resDto.setErrorCode("0000");
					resDto.setErrorMsg("认购折扣审批流程节点人员未设置!");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}
			}
			
			if(reqDto.getDiscountApproval().equals("0") && reqDto.getDiscountApproval() != null){
				//动态获取认购流程KEY
				startProcessKey_rg = activitiProcessService.getProcessKey(reqDto.getMerchantId(), subscribe.getProjectId(), ProcessTypeEnums.PROCESS_KEY_5);
				if(StringUtils.isEmpty(startProcessKey_rg)){
					resDto.setErrorCode("0000");
					resDto.setErrorMsg("项目未设置认购流程，请去项目流程菜单配置!");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}
				// 检查流程节点是否已设置人员（认购审批）
				String processKey = startProcessKey_rg;
				boolean isSeting = activitiProcessService.checkNodeUser(reqDto.getMerchantId(), subscribe.getProjectId(), processKey);
				if (!isSeting) {
					resDto.setErrorCode("0000");
					resDto.setErrorMsg("认购审批流程节点人员未设置!");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}
			}
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			//1、修改客户认筹
			SubscribeDto subscribeDto = new SubscribeDto();
			subscribeDto.setId(subscribe.getId());
			subscribeDto.setProjectCode(reqDto.getProjectCode());
			if(reqDto.getPayDepositId() != null && !"".equals(reqDto.getPayDepositId()) && !"null".equals(reqDto.getPayDepositId())){
				subscribeDto.setPayDepositId(Long.parseLong(reqDto.getPayDepositId()));
			}
			subscribeDto.setPayDepositCode(reqDto.getPayDepositCode());
			if(reqDto.getPayDepositMoney() != null && !"".equals(reqDto.getPayDepositMoney())){
				subscribeDto.setPayDepositMoney(new BigDecimal(reqDto.getPayDepositMoney()));
			}
			if(reqDto.getSubscribeCode() != null && !"".equals(reqDto.getSubscribeCode())){
				subscribeDto.setSubscribeCode(reqDto.getSubscribeCode());
			}
			subscribeDto.setRoomId(Long.parseLong(reqDto.getRoomId()));
			if(StringUtils.isNotEmpty(reqDto.getCalculateArea())){
				subscribeDto.setCalculateArea(new BigDecimal(reqDto.getCalculateArea()));
			}
			//折前单价
			if(StringUtils.isNotEmpty(reqDto.getDiscountPrice())){
				subscribeDto.setConversionPrice(new BigDecimal(reqDto.getDiscountPrice()));
			}
			//折前总价
			if(StringUtils.isNotEmpty(reqDto.getDiscountTotalPrice())){
				/*subscribeDto.setLumpsumPrice(new BigDecimal(Double.valueOf(reqDto.getDiscountTotalPrice())*10000));*/
				subscribeDto.setLumpsumPrice(new BigDecimal(Double.valueOf(reqDto.getDiscountTotalPrice())));
			}
			//折扣金额
			if(StringUtils.isNotEmpty(reqDto.getDiscountAmount())){
				subscribeDto.setDiscountAmount(new BigDecimal(reqDto.getDiscountAmount()));
			}
			//折扣比例
			if(StringUtils.isNotEmpty(reqDto.getDiscountRate())){
				subscribeDto.setDiscountRate(new BigDecimal(reqDto.getDiscountRate()));
			}
			//是否折扣审批
			subscribeDto.setDiscountApproval(reqDto.getDiscountApproval());
			//优惠说明
			if(StringUtils.isNotEmpty(reqDto.getPreferentialReasons())){
				subscribeDto.setPreferentialReasons(reqDto.getPreferentialReasons());
			}
			subscribeDto.setDiscountNote(reqDto.getDiscountNote());
			//认购单价
			if(StringUtils.isNotEmpty(reqDto.getContractPrice())){
				subscribeDto.setSubscribePrice(new BigDecimal(reqDto.getContractPrice()));
			}
			//认购总价（即为认购合同金额）
			if(StringUtils.isNotEmpty(reqDto.getContractAmount())){
				/*subscribeDto.setSubscribeAmount(new BigDecimal(Double.valueOf(reqDto.getContractAmount())*10000));*/
				subscribeDto.setSubscribeAmount(new BigDecimal(Double.valueOf(reqDto.getContractAmount())));
			}
			//应收定金
			if(StringUtils.isNotEmpty(reqDto.getDepositReceivable())){
				subscribeDto.setDepositReceivable(new BigDecimal(reqDto.getDepositReceivable()));
			}
			if(StringUtils.isNotEmpty(reqDto.getDueTime())){
				subscribeDto.setDueTime(sdf.parse(reqDto.getDueTime()));
				subscribeDto.setConversionSignDate(sdf.parse(reqDto.getDueTime()));
			}
			subscribeDto.setPaymentMethod(reqDto.getPaymentMethod());
			subscribeDto.setDealCategory(reqDto.getDealCategory());
			if(StringUtils.isNotEmpty(reqDto.getSubscribeDate())){
				subscribeDto.setDidTime(sdf.parse(reqDto.getSubscribeDate()));
				subscribeDto.setSubscribeDate(sdf.parse(reqDto.getSubscribeDate()));
			}
			subscribeDto.setRemark(reqDto.getRemark());
			subscribeDto.setAuditStatus(reqDto.getAuditStatus());
			subscribeDto.setUpdateUserId(Long.parseLong(reqDto.getUserId()));
			//方案类别（0 低价；1 折扣）
			if(reqDto.getFloorType() != null && !"".equals(reqDto.getFloorType())){
				subscribeDto.setFloorType(reqDto.getFloorType());
			}
			//折后金额
			if(reqDto.getDiscountAfterAmount() != null && !"".equals(reqDto.getDiscountAfterAmount())){
				subscribeDto.setDiscountAfterPrice(new BigDecimal(reqDto.getDiscountAfterAmount()));
			}
			//推荐人信息
			if(StringUtils.isNotEmpty(reqDto.getReferenceId())){
				subscribeDto.setReferenceId(Long.valueOf(reqDto.getReferenceId()));
			}
			if(StringUtils.isNotEmpty(reqDto.getReferenceName())){
				subscribeDto.setReferenceName(reqDto.getReferenceName());
			}
			if(null != reqDto.getReferenceProportion() && !"null".equals(reqDto.getReferenceProportion())
					&& reqDto.getReferenceProportion().length() != 0){
				subscribeDto.setReferenceProportion(new BigDecimal(reqDto.getReferenceProportion()));
			}
			subscribeService.update(subscribeDto);
			
			//更新客户信息
			CustomerDto customerDto = new CustomerDto();
			customerDto.setId(subscribe.getCustomerId());
			customerDto.setCustomerName(reqDto.getMemberName());
			customerDto.setPeDocumentType(reqDto.getDocumentType());
			customerDto.setPeDocumentNumber(reqDto.getDocumentNumber());
			customerDto.setCustomerPhone(reqDto.getMobile());
			customerDto.setPeContactAddress(reqDto.getMailPost());
			customerDto.setPePostcode(reqDto.getPostcode());
			customerService.update(customerDto);
			
			/**
			 * dealCategoryList（成交类别列表）
			 * 1、先删除原来记录
			 * 2、再新增现有记录
			 */
			if(reqDto.getDealCategoryList() != null && reqDto.getDealCategoryList().size() >0){
				TransactionRelationDto tranRelaDto = new TransactionRelationDto();
				tranRelaDto.setBusinessId(subscribe.getId());
				transactionRelationService.destroy(tranRelaDto);
				
				for(int d=0;d<reqDto.getDealCategoryList().size();d++){
					TransactionRelationDto tranDto = new TransactionRelationDto();
					tranDto.setMerchantId(subscribe.getMerchantId());
					tranDto.setProjectCode(subscribe.getProjectCode());
					tranDto.setProjectId(subscribe.getProjectId());
					tranDto.setBusinessId(subscribe.getId());
					tranDto.setRelationType(RelationTypeEnum.SUBSCRIBE.getNo());
					tranDto.setRelationAgentid(Long.valueOf(reqDto.getDealCategoryList().get(d).getRelationAgentId()));
					tranDto.setProportionCommission(reqDto.getDealCategoryList().get(d).getProportionCommission());
					User userModel = userService.selectById(Long.valueOf(reqDto.getDealCategoryList().get(d).getRelationAgentId()));
					tranDto.setUserCode(userModel.getUserCode());
					tranDto.setAccessCode(subscribe.getAccessCode());
					tranDto.setCreateUserId(subscribe.getCreateUserId());
					tranDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					transactionRelationService.create(tranDto);
				}
				
			}
			
			//修改客户家庭成员
			CommonResDTO commonResDTO = editCusFamily(subscribe, reqDto);
			if(StringUtils.isNotEmpty(commonResDTO.getErrorCode())){
				resDto.setErrorCode(commonResDTO.getErrorCode());
				resDto.setErrorMsg(commonResDTO.getErrorMsg());
				resDto.setResult(ResultEnum.FAILURE.getNo());
			}
			
			/**
			 * 1.提交认购审核,修改状态为审核中,保存流程ID
			 * 2.修改房源状态认购
			 */
			String pid = null;
			@SuppressWarnings("unused")
			String flag = null;
			if(reqDto.getDiscountApproval().equals("1") && reqDto.getDiscountApproval() != null && reqDto.getAuditStatus().equals("1") && reqDto.getAuditStatus() != null){
				//初始化销控业务异常表
				BusinessAbnormaDto businessAbnormaDto=new BusinessAbnormaDto();
				businessAbnormaDto.setBusinessId(subscribe.getId());
				businessAbnormaDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_0.getNo());
				businessAbnormaDto.setAuditStatus(AuditStatusEnum.TOSUBMIT.getNo());
				businessAbnormaDto.setAccessCode(subscribe.getAccessCode());
				businessAbnormaDto.setUserCode(subscribe.getUserCode());
				businessAbnormaDto.setMerchantId(reqDto.getMerchantId());
				businessAbnormaDto.setCreateUserId(Long.valueOf(reqDto.getUserId()));
				businessAbnormaDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				businessAbnormaDto.setUpdateUserId(Long.valueOf(reqDto.getUserId()));
				businessAbnormaDto.setUpdateTime(new Date());
				BusinessAbnormaDto baDto = businessAbnormaService.create(businessAbnormaDto);
				if(baDto != null){
					flag = "1";
					Map<String, Object> variables = new HashMap<String, Object>();
					
					User user = userService.selectById(Long.valueOf(reqDto.getUserId()));
					identityService.setAuthenticatedUserId(user.getUserAccount());
					pid=activitiProcessService.startProcessInstance(user.getMerchantId(), subscribe.getProjectId(), startProcessKey_rgzk, subscribe.getId().toString(), variables);

					BusinessAbnormaDto updateBADto = new BusinessAbnormaDto();
					updateBADto.setId(baDto.getId());
					updateBADto.setProcInstId(pid);
					updateBADto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
					businessAbnormaService.update(updateBADto);
					//修改房源状态为认购
					ProjectRoomDto projectRoomDto=new ProjectRoomDto();
					projectRoomDto.setId(subscribeDto.getRoomId());
					projectRoomDto.setRoomStatus(RoomStatusEnum.BUY.getNo());
					projectRoomService.update(projectRoomDto);
				}
			}else if(reqDto.getDiscountApproval().equals("0") && reqDto.getDiscountApproval() != null){
				if(reqDto.getAuditStatus().equals("1") && reqDto.getAuditStatus() != null){
					flag = "2";
					Map<String, Object> variables = new HashMap<String, Object>();
					User user = userService.selectById(Long.valueOf(reqDto.getUserId()));
					identityService.setAuthenticatedUserId(user.getUserAccount());
					pid=activitiProcessService.startProcessInstance(user.getMerchantId(), subscribe.getProjectId(), startProcessKey_rg, subscribe.getId().toString(), variables);
					SubscribeDto updateDto = new SubscribeDto();
					updateDto.setId(subscribe.getId());
					updateDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
					updateDto.setProcInstId(pid);
					subscribeService.update(updateDto);
					//修改房源状态为认购
					ProjectRoomDto projectRoomDto=new ProjectRoomDto();
					projectRoomDto.setId(subscribeDto.getRoomId());
					projectRoomDto.setRoomStatus(RoomStatusEnum.BUY.getNo());
					projectRoomService.update(projectRoomDto);
				}
			}
			
			// 4.5、新增合同附件【图片】
			if (reqDto.getImageList() != null) {
				List<ImageListReq> imageList = reqDto.getImageList();
				CommonResDTO commonResDto_imge = editSubscribeImage(subscribe, imageList);
				if (StringUtils.isNotEmpty(commonResDto_imge.getErrorCode())) {
					// 抛出异常
					throw new Exception("image");
				}
			}
			
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		}catch(Exception e){
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("修改认购失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}
	
	/**
	 * 修改客户认购家庭成员
	 * @param reqDto
	 * @return
	 */
	public CommonResDTO editCusFamily(Subscribe subscribe, EditSubscribeReqDto reqDto) {
		CommonResDTO resDto = new CommonResDTO();
		try{
			//1、修改认购家庭成员
			//1.1、先删除家庭成员
			//1.2、再添加新的家庭成员
			//删除客户原有家庭成员,修改del_flag = 1
			FamilyMemberDto fmDto_update = new FamilyMemberDto();
			fmDto_update.setBuyId(subscribe.getId());
			List<FamilyMember> familyMemberList = familyMemberService.selectListByDto(fmDto_update);
			if(familyMemberList != null && familyMemberList.size() > 0){
				for(FamilyMember familyMember : familyMemberList){
					FamilyMemberDto fmDto_del = new FamilyMemberDto();
					fmDto_del.setId(familyMember.getId());
					familyMemberService.destroy(fmDto_del);
				}
			}
			
			FamilyMemberDto fmDto = new FamilyMemberDto();
			if(reqDto.getCustomerFamilyList() != null){
				List<CustomerFamilyListReq> cusFmReqList = reqDto.getCustomerFamilyList();
				int index = 0;
				for (CustomerFamilyListReq family: cusFmReqList) {
					fmDto = new FamilyMemberDto();
					fmDto.setCustomerId(subscribe.getCustomerId());
					fmDto.setProjectId(subscribe.getProjectId());
					fmDto.setProjectCode(subscribe.getProjectCode());
					fmDto.setBuyId(subscribe.getId());
					fmDto.setMemberName(family.getMemberName());
					fmDto.setSex(SexEnum.UNKNOW.getNo());
					fmDto.setDocumentType(family.getDocumentType());
					fmDto.setDocumentNumber(family.getDocumentNumber());
					fmDto.setMobile(family.getMobile());
					fmDto.setMemberType(MemberTypeEnum.SUBSCRIBE.getNo());
					fmDto.setMailPost(family.getMailPost());
					fmDto.setPostcode(family.getPostcode());
					if(index == 0){
						fmDto.setIsDefault("1");
					}else{
						fmDto.setIsDefault("0");
					}
					fmDto.setMerchantId(subscribe.getMerchantId());
					fmDto.setUserCode(subscribe.getUserCode());
					fmDto.setAccessCode(subscribe.getAccessCode());
					fmDto.setCreateUserId(subscribe.getCreateUserId());
					fmDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					fmDto.setRemark("认购家庭成员");
					familyMemberService.create(fmDto);
					index++;
				}
			}
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		}catch(Exception e){
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("修改认购家庭成员失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}
	
	/**
	 * 编辑合同附件【图片】
	 * 
	 * @param subscribeDto 认购记录
	 * @param imageList 图片列表
	 * @return 
	 */
	public CommonResDTO editSubscribeImage(Subscribe subscribe, List<ImageListReq> imageList){
		CommonResDTO resDto = new CommonResDTO();
		try {
			for (ImageListReq image: imageList) {
				// 上传头像后缀名：例如【.jpg】（如入参为0 则代表图片保持不变；入参为 1 则代表改图片做删除）
				if ("1".equals(image.getHeadType())) {
					ImageDto dto_img = new ImageDto();
					dto_img.setSmallUrl(image.getSignedUrl());
					imageService.destroy(dto_img);
				} else if (!"1".equals(image.getHeadType()) && !"0".equals(image.getHeadType())) {
					String imgName = SequencesGenerator.getUUID("IMG")+ image.getHeadType();
					String result = FileUploadPorxyUtil.appPost(fileUploadUrl, image.getSignedUrl(), imgName);
					JSONObject resultJson = JSON.parseObject(result);
					String postResult = resultJson.getString("result");
					if (!"1".equals(postResult)) {
						resDto.setResult(ResultEnum.FAILURE.getNo());
						resDto.setErrorCode("00000");
						resDto.setErrorMsg("认购合同附件图片上传失败");
						return resDto;
					}
					String postUrl = resultJson.getString("url");
					ImageDto imageDto = new ImageDto();
					imageDto.setObjectId(subscribe.getId());
					imageDto.setSmallUrl(postUrl);
					imageDto.setImgType(ImgTypeEnum.SUBSCRIBE.getNo());
					imageDto.setMerchantId(subscribe.getMerchantId());
					imageDto.setUserCode(subscribe.getUserCode());
					imageDto.setAccessCode(subscribe.getAccessCode());
					imageDto.setRemark("认购合同附件");
					imageDto.setCreateUserId(subscribe.getCreateUserId());
					imageDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					imageService.create(imageDto);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("编辑合同附件失败!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}
	
	/**
	 * 新增客户认购推送push消息
	 * 
	 * @param subscribeDto 认购记录
	 * @return 
	 */
	public CommonResDTO addSubscribeNotice(Long id, String flag){
		CommonResDTO resDto = new CommonResDTO();
		try {
			Subscribe subscribeDto = subscribeService.selectById(id);
			//待审核数据,发送消息
			if(AuditStatusEnum.AUDIT.getNo().equals(subscribeDto.getAuditStatus())){
				//客户
				String cusName = "";
				Customer customer = customerService.selectById(subscribeDto.getCustomerId());
				if(customer != null){
					cusName = customer.getCustomerName();
				}
				
				/**
				 * 消息接收人
				 * 1、根据审批节点人员确定
				 */
				//获取当前项目下审批节点人map
				ProjectSettingDto pDto = new ProjectSettingDto();
				pDto.setProjectCode(subscribeDto.getProjectCode());
				ProjectSetting pObj = projectSettingService.selectByDto(pDto);
				Map<String, Object> variables = new HashMap<String, Object>();
				variables.put("projectApprovalUser", pObj.getProjectLeader());
				variables.put("marketingApprovalUser", pObj.getSaleLeader());
				variables.put("caseApprovalUser", pObj.getFieldLeader());
				variables.put("financeApprovalUser", pObj.getFinanceLeader());
				variables.put("saleManagerApprovalUser", pObj.getMaLeader());
				
				//获取审批人userId
				List<User> userList = new ArrayList<User>();
				HistoricProcessInstance historicProcessInstance = null;
				if("1".equals(subscribeDto.getDiscountApproval())){
					BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
					businessAbnormaDto.setBusinessId(subscribeDto.getId());
					businessAbnormaDto.setBusinessType(BusinessTypeEnum.SUBSCRIBE.getNo());
					businessAbnormaDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
					List<BusinessAbnorma> businessAbnormaList = businessAbnormaService.selectListByDto(businessAbnormaDto);
					if(businessAbnormaList.size() > 0 && businessAbnormaList != null){
						historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(businessAbnormaList.get(0).getProcInstId()).singleResult();
					}else{
						BusinessAbnormaDto baDto = new BusinessAbnormaDto();
						baDto.setBusinessId(subscribeDto.getId());//业务ID
						List<BusinessAbnorma> baList = businessAbnormaService.selectListByDto(baDto);
						if(baList.size() > 0){
							for(BusinessAbnorma baEntity : baList){
								if("3".equals(baEntity.getAuditStatus())){
									historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(subscribeDto.getProcInstId()).singleResult();
								}
							}
						}
					}
				}else{
					historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(subscribeDto.getProcInstId()).singleResult();
				}
				BpmnModel model = repositoryService.getBpmnModel(historicProcessInstance.getProcessDefinitionId());  
				if(model != null) {  
					Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();  
					for(FlowElement e : flowElements) { 
						if(e instanceof UserTask){
							List<String> userIds = activitiProcessService.getNodeUserId(subscribeDto.getMerchantId(),null,historicProcessInstance.getProcessDefinitionId(),e.getId());
							for(String userId : userIds){
								User user = new User();
								user.setId(Long.valueOf(userId));
								userList.add(user);
							}
						}
					}  
				}
				
				//项目
				/*String proName = "";
				Project project = null;
				if(subscribeDto.getProjectId() != null){
					project = projectService.selectById(subscribeDto.getProjectId());
					if(project != null){
						proName = project.getProjectName();
					}
				}*/
				
				//获取归属人
				UserDto userDto = new UserDto();
				userDto.setUserCode(customer.getUserCode());
				User userAgent_gsr = userService.selectByDto(userDto);
				
				/*String pushType = "SHSQ";*/
				
				//获取经纪人
				/*String userName = "";
				TransactionRelationDto transactionRelationDto = new TransactionRelationDto();
				transactionRelationDto.setBusinessId(subscribeDto.getId());
				List<TransactionRelation> transactionRelationList = transactionRelationService.selectListByDto(transactionRelationDto);
				if(transactionRelationList.size() > 0){
					for(int i=0;i< transactionRelationList.size() ;i++){
						User user = userService.selectById(transactionRelationList.get(i).getRelationAgentid());
						if(user.getUserName() != null && !"".equals(user.getUserName())){
							if(transactionRelationList.size() == 1){
								userName = user.getUserName();
							}else{
								userName += "；经纪人"+(i+1)+"："+user.getUserName();
							}
						}
					}
				}*/
				
				//认购折扣, 获取字典表dictionary_value = 'NT10' 的消息模板
				//消息模板: 认购折扣：购房折扣审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}
				if(flag == "1"){
					String msgTemp = "购房折扣审批申请。房号：${roomName}；客户：${customer}；归属人：${agent}";
					String sendMsg = "";
					DictionaryDto dicDto = new DictionaryDto();
					dicDto.setDictionaryValue("NT10");
					Dictionary dic = dictionaryService.selectByDto(dicDto);
					if(dic != null){
						msgTemp = dic.getDictionaryName();
					}
					//项目房间
					String roomContent = "";
					ProjectRoom room = projectRoomService.selectById(subscribeDto.getRoomId());
					if(room != null){
						roomContent = room.getCombinedName();
					}
					sendMsg = msgTemp.replace("${roomName}", roomContent)
							.replace("${customer}", cusName)
							.replace("${agent}", userAgent_gsr.getUserName());
//							.replace("${agent}", userName);
					//创建提醒消息及消息发送人信息
					Map<String, String> noticeParamMap = new HashMap<String, String>();
					noticeParamMap.put("noticeDicId",  dic.getId()+"");
					noticeParamMap.put("noticeTempType", "NT10");
					noticeParamMap.put("sendMsg", sendMsg);
					noticeParamMap.put("title", "认购折扣审批申请");
					noticeParamMap.put("merchantId", String.valueOf(subscribeDto.getMerchantId()));
					noticeParamMap.put("projectCode", subscribeDto.getProjectCode());
					noticeParamMap.put("userCode", subscribeDto.getUserCode());
					noticeParamMap.put("accessCode", subscribeDto.getAccessCode());
					noticeParamMap.put("createUserId", String.valueOf(subscribeDto.getCreateUserId()));
					/*
					 * (ym) 提醒内容增加超链接 start
					 * */
					Map<String,String> replaceValuesMap=new HashMap<String,String>();
					replaceValuesMap.put(MsgUtil.ROOM_ID, String.valueOf(room.getId()));
					replaceValuesMap.put(MsgUtil.ROOM_NAME, roomContent);
					replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(customer.getId()));
					replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, customer.getCustomerName());
					replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
					replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
			    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
			    	/*
					 * (ym) 提醒内容增加超链接 end
					 * */
			    	String action = "认购折扣提交审核提醒";
					resDto = cusAppNoticeManage.createNotice(noticeParamMap, userList, action);
					
					//推送消息
					if("1".equals(resDto.getResult())){
						//推送消息待处理......
						//pushMsg(project.getProjectCode(), proName, "NT10","认购折扣审批申请", userName);
					}
					
				//认购, 获取字典表dictionary_value = 'NT08' 的消息模板
				//消息模板: 认购：认购审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}	
				}else if(flag == "2"){
					String msgTemp = "认购审批申请。房号：${roomName}；客户：${customer}；归属人：${agent}";
					String sendMsg = "";
					DictionaryDto dicDto = new DictionaryDto();
					dicDto.setDictionaryValue("NT08");
					Dictionary dic = dictionaryService.selectByDto(dicDto);
					if(dic != null){
						msgTemp = dic.getDictionaryName();
					}
					//项目房间
					String roomContent = "";
					ProjectRoom room = projectRoomService.selectById(subscribeDto.getRoomId());
					if(room != null){
						roomContent = room.getCombinedName();
					}
					sendMsg = msgTemp.replace("${roomName}", roomContent)
							.replace("${customer}", cusName)
							.replace("${agent}", userAgent_gsr.getUserName());
//							.replace("${agent}", userName);
					//创建提醒消息及消息发送人信息
					Map<String, String> noticeParamMap = new HashMap<String, String>();
					noticeParamMap.put("noticeDicId",  dic.getId()+"");
					noticeParamMap.put("noticeTempType", "NT08");
					noticeParamMap.put("sendMsg", sendMsg);
					noticeParamMap.put("title", "认购审批申请");
					noticeParamMap.put("merchantId", String.valueOf(subscribeDto.getMerchantId()));
					noticeParamMap.put("projectCode", subscribeDto.getProjectCode());
					noticeParamMap.put("userCode", subscribeDto.getUserCode());
					noticeParamMap.put("accessCode", subscribeDto.getAccessCode());
					noticeParamMap.put("createUserId", String.valueOf(subscribeDto.getCreateUserId()));
					/*
					 * (ym) 提醒内容增加超链接 start
					 * */
					Map<String,String> replaceValuesMap=new HashMap<String,String>();
					replaceValuesMap.put(MsgUtil.ROOM_ID, String.valueOf(room.getId()));
					replaceValuesMap.put(MsgUtil.ROOM_NAME, roomContent);
					replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(customer.getId()));
					replaceValuesMap.put(MsgUtil.CUSTOMER_NAME,cusName);
					replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
					replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
			    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
			    	/*
					 * (ym) 提醒内容增加超链接 end
					 * */
			    	String action = "认购提交审核提醒";
					resDto = cusAppNoticeManage.createNotice(noticeParamMap, userList, action);
					
					//推送消息
					if("1".equals(resDto.getResult())){
						//推送消息待处理......
						//pushMsg(project.getProjectCode(), proName, "NT08","认购审批申请", flag);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("新增认购消息失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}
	
	public void pushMsg(String projectCode,String projectName,String noticeTempType,String actionTitle, String flag) throws Exception{
		//1、查询认购审核申请相关推送消息
		// NT08: 认购审核申请
		List<MessageReceiverDto> msgRecList = new ArrayList<MessageReceiverDto>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
 		int year = calendar.get(Calendar.YEAR);
 		int month = calendar.get(Calendar.MONTH) + 1;
 		int day = calendar.get(Calendar.DAY_OF_MONTH);
// 		String issueTimeBefore = year + "-" + month + "-" + day + " 00:00:00"; 
 		String issueTimeAfter = year + "-" + month + "-" + day + " 23:59:59"; 
 		MessageReceiverDto withHouseMrDto = new MessageReceiverDto();
 		withHouseMrDto.setNoticeTempType(noticeTempType);
 		withHouseMrDto.setIsSend(IsSendEnum.UNSEND.getNo());
 		//loseCusMrDto.setIssueTimeBefore(sdf.parse(issueTimeBefore));
 		//推送所有小于 issueTimeAfter 时间的所有消息
 		withHouseMrDto.setIssueTimeAfter(sdf.parse(issueTimeAfter));
   	 	List<MessageReceiverDto> withHouseMrList = messageReceiverService.selectPushMsgListByDto(withHouseMrDto);
   	 	if(withHouseMrList != null){
   	 		for(MessageReceiverDto withHouseMr: withHouseMrList){
   	 			msgRecList.add(withHouseMr);
   	 		}
   	 	}
   	 	
   	 	if(msgRecList != null && msgRecList.size() > 0){
   	 		String noticeIds = "";
   	 		String msgRecIds = "";
   	 		Set<String> noticeIdSet = new HashSet<String>();
   	 		for(MessageReceiverDto msgRecDto: msgRecList){
   	 			//开始推送消息
	   	 		Map<String, String> pushMap = new HashMap<String, String>();
	   	 		if(flag == "1"){
	   	 			pushMap.put("action", "认购折扣提交审核提醒");
	   	 		}else{
	   	 			pushMap.put("action", "认购提交审核提醒");
	   	 		}
		   	 	pushMap.put("remindCategoryId", String.valueOf(msgRecDto.getDictionaryId()));
//		   	 	pushMap.put("pushType", msgRecDto.getNoticeTempType());
		   	 	pushMap.put("pushType", "SHSQ");
		   	    pushMap.put("projectCode",projectCode);
		   	    pushMap.put("projectName", projectName);
				String context = msgRecDto.getContent();
				appPushService.pushMessage(String.valueOf(msgRecDto.getReceiverId()), context,
					msgRecDto.getTitle(), pushMap);
				
				//消息ID,Set
				noticeIdSet.add(String.valueOf(msgRecDto.getNoticeId()));
				//消息接收人ID'S
				if(StringUtils.isNotEmpty(msgRecIds)){
					msgRecIds += ",";
				}
				msgRecIds += String.valueOf(msgRecDto.getId());
   	 		}
   	 		//需更新消息ID'S
   	 		if(!noticeIdSet.isEmpty()){
				for(String noticeId: noticeIdSet){
					if(StringUtils.isNotEmpty(noticeIds)){
						noticeIds += ",";
					}
					noticeIds += noticeId;
	   	 		}
   	 		}
   	 		//更新消息
   	 		NoticeDto noticeDto = new NoticeDto();
   	 		noticeDto.setIsSend(IsSendEnum.SEND.getNo());
   	 		noticeService.updates(noticeDto, noticeIds);
   	 		//更新接收人
   	 		MessageReceiverDto updateMRDto = new MessageReceiverDto();
   	 		updateMRDto.setIsSend(IsSendEnum.SEND.getNo());
   	 		messageReceiverService.updates(updateMRDto, msgRecIds);
   	 	}
	}
	
}
